;
(function(_$) {

    const question = {
        init: function(selector, options = {}, dt) {
            const qus = {
                _selectorContainer: selector,
                _questionItem: undefined,
                _zTreeAddChapter: undefined,
                _questionAddForm: null,
                _questionContentContainer: undefined,
                _listeners: {
                    saveStart: options.saveStart,
                    saveSuccess: options.saveSuccess,
                    saveCatch: options.saveCatch,
                    addStart: options.addStart,
                    addSuccess: options.addSuccess,
                    addCatch: options.addCatch,
                },           
                destroy: function() {
                    if (this._zTreeAddChapter) {
                        this._zTreeAddChapter.destroy();
                    }
                    if (this._questionItem) {
                        this._questionItem.destroy();
                    }
                    _$(this._selectorContainer).empty().remove();  
                },
                getQuestion: function() {
                    console.warn(this);
                    const val = this._questionItem.getQuestion();
                    console.warn(val);
                    if (!val) {
                        return;
                    }
                    return {
                        base: getQuestionBase(this),
                        content: val
                    };
                },
                getQuestionBase: function() {
                    return getQuestionBase(this);
                },
                save: function() {
                    _$(`${this._selectorContainer} #${this._questionAddForm} `).submit();
                },
                initData: function(id) {
                    console.warn("initData");
                    _$(qus._selectorContainer).loading({ message: "加载中...", zIndex: 2000, });
                    getQuestion(id).then(({ data }) =>{
                        initData(qus, options, data);
                    }).finally(() => {
                        _$(qus._selectorContainer).loading("stop");
                    });
                },
                reset: function() {
                    console.warn("reset");
                    if (this._questionItem) {
                        this._questionItem.reset();
                    }
                },
            };
            _$(qus._selectorContainer).empty().append(getHtml(qus));
            
            questionAddFormValidRules(qus);
            bindListener(qus);
            getSysConfig(qus, options).then(() => {
                initData(qus, options, dt);
            });
            return qus;
        },
    };
    
    function getHtml(qus) {
        qus._questionAddForm = `question-add-form-${Date.now()}`;
        qus._questionContentContainer = `question-content-container-${Date.now()}`;
        return `
        <form class="form-horizontal know-form" role="form" id="${qus._questionAddForm}">
            <fieldset>
                <legend>基本信息</legend>
                <div class="base-item-container">
                    <div class="form-group base-item">
                        <label for="grade_code" class="col-sm-2 control-label">年级</label>
                        <div class="col-sm-10">
                            <select class="form-control form-item-val" name="grade_code" id="grade_code">
                            </select>
                        </div>
                    </div>
                    <div class="form-group base-item">
                        <label for="subject_code" class="col-sm-2 control-label">科目</label>
                        <div class="col-sm-10">
                            <select class="form-control form-item-val" name="subject_code" id="subject_code"
                                data-rule-required="true" data-msg-required="科目为必填项">
                            </select>                            
                        </div>
                    </div>
                </div>
                <div class="base-item-container">
                    <div class="form-group base-item">
                        <label for="material_uuid" class="col-sm-2 control-label">教材/资料</label>
                        <div class="col-sm-10">
                            <select class="form-control form-item-val" name="material_uuid" id="material_uuid">
                            </select>
                        </div>
                    </div>
                    <div class="form-group base-item">
                        <label for="chapter-name" class="col-sm-2 control-label">章节</label>
                        <div class="col-sm-10 add-question-chapter-wrapper">
                            <input type="text" class="form-control form-item-val" name="chapter_name" id="chapter_name" placeholder="请输入章节" readonly>
                            <input type="hidden" name="chapter_uuid" id="chapter_uuid">
                            <ul class="add-chapter-tree ztree"></ul>
                        </div>
                    </div>
                </div>
                <div class="base-item-container">
                    <div class="form-group base-item">
                        <label for="type_code" class="col-sm-2 control-label">题型</label>
                        <div class="col-sm-10">
                            <select class="form-control form-item-val" name="type_code" id="type_code"
                                data-rule-required="true" data-msg-required="题型为必填项">
                            </select>
                        </div>
                    </div>
                    <div class="form-group base-item">
                        <label for="type_alias" class="col-sm-2 control-label">题型别名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control form-item-val" name="type_alias" id="type_alias" placeholder="请输入题型别名">
                        </div>
                    </div>
                </div>
                <div class="base-item-container">
                    <div class="form-group base-item">
                        <label for="difficulty_code" class="col-sm-2 control-label">难易度</label>
                        <div class="col-sm-10">
                            <select class="form-control form-item-val" name="difficulty_code" id="difficulty_code">
                            </select>
                        </div>
                    </div>
                    <div class="form-group base-item">
                        <label for="star_code" class="col-sm-2 control-label">星级</label>
                        <div class="col-sm-10">
                            <select class="form-control form-item-val" name="star_code" id="star_code">
                            </select>
                        </div>                        
                    </div>
                </div>
                <div class="base-item-container">
                    <div class="form-group base-item">
                        <label for="score" class="col-sm-2 control-label">分数</label>
                        <div class="col-sm-10">
                            <input type="number" class="form-control form-item-val" name="score" id="score" placeholder="请输入分数" value="0">
                        </div>
                    </div>
                    <div class="form-group base-item">
                        <label for="star_code" class="col-sm-2 control-label">做题人数</label>
                        <div class="col-sm-10">
                            <input type="number" class="form-control form-item-val" name="people" id="people" placeholder="请输入做题人数" value="100">
                        </div>                        
                    </div>
                </div>
                <div class="base-item-container">
                    <div class="form-group base-item">
                        <label for="order" class="col-sm-2 control-label">序号</label>
                        <div class="col-sm-10">
                            <input type="number" class="form-control" name="order_number" id="order_number" placeholder="请输入序号" value="0">
                        </div>
                    </div>
                </div>
            </fieldset>
            <fieldset>
                <legend>试题信息</legend>
                <div class="${qus._questionContentContainer}"></div>
            </fieldset>
            <input type="hidden" name="id">
            <input type="hidden" name="tid">
        </form>`;
    }
    
    function bindListener(qus) {
        _$(`${qus._selectorContainer} #grade_code`).change(function() {
            getMaterialList(qus).finally(() => {
                _$(`${qus._selectorContainer} .add-question-chapter-wrapper input[name='chapter_name']`).val("");
                _$(`${qus._selectorContainer}.add-question-chapter-wrapper input[name='chapter_uuid']`).val("");
            });
        });

        _$(`${qus._selectorContainer} #subject_code`).change(function() {
            getMaterialList(qus).finally(() => {
                _$(`${qus._selectorContainer} .add-question-chapter-wrapper input[name='chapter_name']`).val("");
                _$(`${qus._selectorContainer} .add-question-chapter-wrapper input[name='chapter_uuid']`).val("");
            });
        });

        _$(`${qus._selectorContainer} select[name='material_uuid']`).change(function(e) {
            initAddChapterTree(qus);
        });

        _$(`${qus._selectorContainer} .add-question-chapter-wrapper input[name='chapter_name']`).focus(function() {
            _$(`${qus._selectorContainer} .add-chapter-tree`).show();
        });

        bindTreeShowListener(`${qus._selectorContainer} .add-chapter-tree`);


        _$(`${qus._selectorContainer} #type_code`).change(function() {
            typeChange(qus);
        });        
        
    }
    
    function typeChange(qus, dt) {
        $(`${qus._selectorContainer} #type_alias`).val(_$(`${qus._selectorContainer} #type_code option:selected`).text());
        console.warn(qus._questionItem);
        if (qus._questionItem) {
            qus._questionItem.destroy();
            qus._questionItem = null;
            console.warn("销毁");
        }
        const type = _$(`${qus._selectorContainer} #type_code option:selected`).val();
        console.warn(qus._questionContentContainer, type);
        if (type === "fill") {
            qus._questionItem = _$.fn.questionFill.init(`.${qus._questionContentContainer}`, qus, dt);
        } else if (type === "single") {
            qus._questionItem = _$.fn.questionSingle.init(`.${qus._questionContentContainer}`, qus, dt);
        } else if (type === "multiple") {
            qus._questionItem = _$.fn.questionMultiple.init(`.${qus._questionContentContainer}`, qus, dt);
        } else if (type === "readAnalysis") {
            qus._questionItem = _$.fn.questionReadAnalysis.init(`.${qus._questionContentContainer}`, qus, dt);
        }
    }

    function getMaterialList(qus) {
        _$(qus._selectorContainer).loading({ message: "加载中...", zIndex: 2000, });
        return know.http.httpGet("/know/AdminTeachingMaterial/list", {
            pageNumber: 1,
            pageSize: Number.MAX_SAFE_INTEGER,
            grade_code: _$(`${qus._selectorContainer} #${qus._questionAddForm}  select[name='grade_code'] option:selected`).val(),
            subject_code: _$(`${qus._selectorContainer} #${qus._questionAddForm}  select[name='subject_code'] option:selected`).val(),
        }).then(({ data: { rows } = {} }) => {
            const htm = rows.map((item) => {
                return `<option value="${item.uuid}">${item.name}</option>`;
            }).join("");
            _$(`${qus._selectorContainer} #${qus._questionAddForm}  select[name='material_uuid']`).empty().append(`<option value="">请选择教材/资料</option>${htm}`);
        }).finally(() => {
            _$(qus._selectorContainer).loading("stop");
        });
    }

    function bindTreeShowListener(selector) {
        _$(selector).mouseenter(function() {
            _$(this).data("coming-leave", false);
        });

        _$(selector).mouseleave(function() {
            _$(this).data("coming-leave", true);
            setTimeout(() => {
                if (_$(this).data("coming-leave")) {
                    console.warn('coming-leave');
                    _$(this).hide();
                }
            }, 100);
        });
    }

    function initAddChapterTree(qus) {
        const relate_uuid = _$(`${qus._selectorContainer} #${qus._questionAddForm}  select[name='material_uuid'] option:selected`).val();
		_$(qus._selectorContainer).loading({ message: "加载中...", zIndex: 2000, });
        return getMaterialChapterTree(relate_uuid).then((ar) => {
            if (qus._zTreeAddChapter) {
				qus._zTreeAddChapter.destroy();
			}
			const chapterTreeSetting = {
				callback: {
					onClick(event, treeId, treeNode, clickFlag) {
						console.warn(event, treeId, treeNode, clickFlag);
                        _$(`${qus._selectorContainer} .add-question-chapter-wrapper input[name='chapter_name']`).val(treeNode.name);
                        _$(`${qus._selectorContainer} .add-question-chapter-wrapper input[name='chapter_uuid']`).val(treeNode.uuid);
					},
				},
				data: {
					simpleData: {
						enable: true
					},
				},
			};
			qus._zTreeAddChapter = $.fn.zTree.init(_$(`${qus._selectorContainer} .add-question-chapter-wrapper .add-chapter-tree`), chapterTreeSetting, ar.map((item) => {
				return {
					id: item.id,
					name: item.name,
					pId: item.parent ? item.parent.id : 0,
					uuid: item.uuid,
				};
			}));
		}).finally(() => {
            _$(qus._selectorContainer).loading("stop");
        });	
	}

    function questionAddFormValidRules(qus) {
        know.form.formValidRules(`${qus._selectorContainer} #${qus._questionAddForm}`, ".form-item-val", () => {
            const id = `${qus._selectorContainer} #${qus._questionAddForm}  input[name="id"]`;
            if (_$(id).val()) {
                questionEdit(qus);
            } else {
                questionAdd(qus);
            }
        });
    }

    function getMaterialChapterTree(relate_uuid) {
        return know.http.httpGet("/know/AdminChapter/tree", {
            relate_uuid
        }).then(({ data = [] }) => {
			const ar = [...data];
			let i = 0;
			while (i < ar.length) {
				const item = ar[i];
				if (item.children.length <= 0) {
					++i;
					continue;
				}
				item.children.forEach((citem) => {
					citem.parent = item;
				});
				ar.splice(i + 1, 0, ...item.children);
				++i;
			}
            return ar;
		});	
	}

    function getQuestionMaxOrder(qus) {
        return know.http.httpGet("/know/AdminQuestion/maxOrder").then(({ data = 0 }) => {
            _$(`${qus._selectorContainer} #${qus._questionAddForm}  #order_number`).val(data + 20);
        });
    }

    function getSysConfig(qus, options) {
        console.warn(qus, options);
        _$(qus._selectorContainer).loading({ message: "加载中...", zIndex: 2000, });
        return know.http.httpGet("/know/AdminSysConfig/list", {
            type: "SUBJECT,GRADE,QUESTION_TYPE,STAR,FREQUENCY",
            pageSize: Number.MAX_SAFE_INTEGER
        }).then(({ data: { rows } = [] }) => {
            const { questionTypeAllow } = options;
            const arSubject = rows.filter((item) => item.type === "SUBJECT").map((item) => `<option value="${item.key}">${item.value}</option>`);
            arSubject.unshift("<option value=\"\">请选择科目</option>");
            const arGrade = rows.filter((item) => item.type === "GRADE").map((item) => `<option value="${item.key}">${item.value}</option>`);
            arGrade.unshift("<option value=\"\">请选择年级</option>");
            const arQuestionTYpe = rows.filter((item) => item.type === "QUESTION_TYPE").filter((item) => !questionTypeAllow || questionTypeAllow.includes(item.key)).map((item) => `<option value="${item.key}">${item.value}</option>`);
            arQuestionTYpe.unshift("<option value=\"\">请选择试题类型</option>");
            const arStar = rows.filter((item) => item.type === "STAR").map((item) => `<option value="${item.key}">${item.value}</option>`);
            arStar.unshift("<option value=\"\">请选择星级</option>");
            const arFreQuency = rows.filter((item) => item.type === "FREQUENCY").map((item) => `<option value="${item.key}">${item.value}</option>`);
            arFreQuency.unshift("<option value=\"\">请选择难易度</option>");
            _$(`${qus._selectorContainer} #grade_code`).empty().append(arGrade.join(""));
            _$(`${qus._selectorContainer} #subject_code`).empty().append(arSubject.join(""));
            _$(`${qus._selectorContainer} #type_code`).empty().append(arQuestionTYpe.join(""));
            _$(`${qus._selectorContainer} #difficulty_code`).empty().append(arFreQuency.join(""));
            _$(`${qus._selectorContainer} #star_code`).empty().append(arStar.join(""));
        }).finally(() => {
            _$(qus._selectorContainer).loading("stop");
        });
    }

    function initData(qus, options, dt) {
        console.warn(qus, options, dt);
        if (dt && dt.base) {
            console.warn("初始化说句", dt.base);
            _$(`${qus._selectorContainer} #grade_code`).val(dt.base.grade_code);
            _$(`${qus._selectorContainer} #subject_code`).val(dt.base.subject_code);
            _$(`${qus._selectorContainer} #difficulty_code`).val(dt.base.difficulty_code);
            _$(`${qus._selectorContainer} #star_code`).val(dt.base.star_code);
            _$(`${qus._selectorContainer} #order_number`).val(dt.base.order_number);
            _$(`${qus._selectorContainer} #score`).val(dt.base.score);
            _$(`${qus._selectorContainer} #people`).val(dt.base.people || 100);
            _$(`${qus._selectorContainer} input[name="tid"]`).val(dt.base.tid);
            _$(`${qus._selectorContainer} input[name="id"]`).val(dt.base.id);
			console.warn(_$(`${qus._selectorContainer} #tid`), `${qus._selectorContainer} #tid`);
            if (dt.base.id || dt.base.tid) {
                _$(`${qus._selectorContainer} #type_code`).val(dt.base.type_code);
                setTimeout(() => {
                    _$(`${qus._selectorContainer} #type_alias`).val(dt.base.type_alias);
                });
            }

            if (dt.base.material_uuid) {
                getMaterialList(qus).finally(() => {
                    _$(`${qus._selectorContainer} #${qus._questionAddForm}  select[name='material_uuid']`).val(dt.base.material_uuid);
                    if (dt.base.chapter_uuid) {
                        return initAddChapterTree(qus).then(() => {
                            const n = qus._zTreeAddChapter.getNodeByParam("uuid", dt.base.chapter_uuid, null);
                            qus._zTreeAddChapter.selectNode(n);
                            $("#" + n.tId + "_a").click();
                        });
                    }
                });
            }
            typeChange(qus, dt);
        }
        if (!dt?.base?.order_number) {
            getQuestionMaxOrder(qus);
        }
    }

    function getQuestionBase(qus) {
        const d = new FormData(_$(`${qus._selectorContainer} #${qus._questionAddForm} `).get(0));
        const delKeys = ["chapter_name", "editorValue", "question-single-option", "question-multiple-option"];
        delKeys.forEach((item) => {
            d.delete(item);
        });
        return Object.fromEntries(d.entries());
    }

    function questionAdd(qus) {
		const questionContent = {
            ...qus._questionItem.getQuestion()
        };
        console.warn(qus);
        qus._listeners.addStart && qus._listeners.addStart();
        return know.http.httpPost("/know/AdminQuestion/add", {
            base: getQuestionBase(qus),
            content: questionContent,
        }).then((res) => {
			noty({
				text: res.msg,
				type: "success",
                layout: "topCenter",
			});
            qus._questionItem.reset();
            getQuestionMaxOrder(qus);
            qus._listeners.addSuccess && qus._listeners.addSuccess();
		}).catch(() => {
            qus._listeners.addCatch && qus._listeners.addCatch();
        });	
	}

    function questionEdit(qus) {
        const d = new FormData(_$(`${qus._selectorContainer} #${qus._questionAddForm} `).get(0));
        const delKeys = ["chapter_name", "editorValue", "question-single-option", "question-multiple-option", "remark", "tid"];
        delKeys.forEach((item) => {
            d.delete(item);
        });
        console.warn(Object.fromEntries(d.entries()));
        const questionContent = {
            ...qus._questionItem.getQuestion()
        };
        console.warn(questionContent);
        qus._listeners.saveStart && qus._listeners.saveStart();
        return know.http.httpPost("/know/AdminQuestion/edit", {
            base: Object.fromEntries(d.entries()),
            content: questionContent,
        }).then((res) => {
			noty({
				text: res.msg,
				type: "success",
                layout: "topCenter",
			});
            _$(`${qus._selectorContainer} #${qus._questionAddForm} input[name='id']`).val("");
            _$(`${qus._selectorContainer} #${qus._questionAddForm} input[name='tid']`).val("");
            qus._listeners.saveSuccess && qus._listeners.saveSuccess();
		}).catch(() => {
            qus._listeners.saveCatch && qus._listeners.saveCatch();
        });	
	}

    function getQuestion(id) {
        return know.http.httpGet("/know/AdminQuestion/getItem", {
            id
        });
    }

    _$.fn.extend({
        questionForm: question,
    });
})($);